//
//  MainPageController.m
//  MyNewProject
//
//  Created by sun on 2018/12/3.
//  Copyright © 2018 sun. All rights reserved.
//
#import "YCMenuView.h"

#import "MainPageController.h"
#import "YXLProduceListViewController.h"
#import "HGCenterBaseTableView.h"
#import "HGSegmentedPageViewController.h"
#import "HGPageViewController.h"
#import "SDCycleScrollView.h"
#import "YXLHomeNotifyView.h"
#import "XMJSWebViewController.h"



#define kPageTabHeight  40

@interface MainPageController() <UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, HGSegmentedPageViewControllerDelegate, HGPageViewControllerDelegate>
@property (nonatomic, strong) HGCenterBaseTableView *tableView;
@property (nonatomic, strong) UIImageView *headerImageView;
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) HGSegmentedPageViewController *segmentedPageViewController;
@property (nonatomic) BOOL cannotScroll;

@property (nonatomic, strong)UIView *topCoverView;

@property (nonatomic, strong) SDCycleScrollView *bannerView;

@property (nonatomic, strong) YXLHomeNotifyView *notifyView;

@property (nonatomic, strong) UIGestureRecognizer *pan;

@property (nonatomic, strong) NSArray *notifyDataArry;

@property (nonatomic, assign) CGFloat  HeaderImageViewHeight;

@end




@implementation MainPageController

- (void)viewDidLoad {
    [super viewDidLoad];

    _HeaderImageViewHeight = SCREEN_WIDTH * bannerRadio + 45;
//    if (@available(iOS 11.0, *)) {
//        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
//    } else {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
    self.gk_navigationBar.hidden = YES;
    //self.gk_navTitle = @"首页";
    //如果使用自定义的按钮去替换系统默认返回按钮，会出现滑动返回手势失效的情况
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self setupSubViews];
    
    [self getTopADData];
    
    [self getNotifyData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateNavigationBarBackgroundColor];
}

#pragma mark - Private Methods
- (void)setupSubViews {
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerImageView;
    //[self.tableView addSubview:self.headerImageView];
    [self.headerImageView addSubview:self.topCoverView];
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT - SKTabBar_Height);
    self.tableView.bounces = NO;
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//
//        NSDictionary *paramDic = @{@"tableView":self.tableView};
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"homePageHeadRefresh" object:paramDic];
//    }];



}

- (void)updateNavigationBarBackgroundColor {
    CGFloat alpha = 0;
    CGFloat currentOffsetY = self.tableView.contentOffset.y;
    if (currentOffsetY >= _HeaderImageViewHeight-SKStatusBar_Height) {
        alpha = 1;
    } else if ((currentOffsetY > SKTopBar_Height) && currentOffsetY < _HeaderImageViewHeight) {
        alpha = (currentOffsetY - SKTopBar_Height) / (_HeaderImageViewHeight - SKTopBar_Height);
    } else {
        alpha = 0;
    }
    self.topCoverView.backgroundColor = SKRGBAColor(255, 255, 255, currentOffsetY/(_HeaderImageViewHeight- self.notifyView.height));
    
    
}

#pragma mark - UIScrollViewDelegate
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    [self.segmentedPageViewController.currentPageViewController makePageViewControllerScrollToTop];
    return YES;
}


/**
 * 处理联动
 * 因为要实现下拉头部放大的问题，tableView设置了contentInset，所以试图刚加载的时候会调用一遍这个方法，所以要做一些特殊处理，
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //第一部分：处理导航栏
    [self updateNavigationBarBackgroundColor];
    
    //第二部分：处理手势冲突
    CGFloat contentOffsetY = scrollView.contentOffset.y;
    //吸顶临界点(此时的临界点不是视觉感官上导航栏的底部，而是当前屏幕的顶部相对scrollViewContentView的位置)
    CGFloat criticalPointOffsetY = [self.tableView rectForSection:0].origin.y -SKStatusBar_Height;
    
    //利用contentOffset处理内外层scrollView的滑动冲突问题
    if (contentOffsetY >= criticalPointOffsetY) {
        /*
         * 到达临界点：
         * 1.未吸顶状态 -> 吸顶状态
         * 2.维持吸顶状态(pageViewController.scrollView.contentOffsetY > 0)
         */
        //“进入吸顶状态”以及“维持吸顶状态”
        self.cannotScroll = YES;
        scrollView.contentOffset = CGPointMake(0, criticalPointOffsetY);
        [self.segmentedPageViewController.currentPageViewController makePageViewControllerScroll:YES];
    } else {
        /*
         * 未达到临界点：
         * 1.吸顶状态 -> 不吸顶状态
         * 2.维持吸顶状态(pageViewController.scrollView.contentOffsetY > 0)
         */
        if (self.cannotScroll) {
            //“维持吸顶状态”
            scrollView.contentOffset = CGPointMake(0, criticalPointOffsetY);
        } else {
            /* 吸顶状态 -> 不吸顶状态
             * pageViewController.scrollView.contentOffsetY <= 0时，会通过代理HGPageViewControllerDelegate来改变当前控制器self.cannotScroll的值；
             */
        }
    }
    
  
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self addChildViewController:self.segmentedPageViewController];
    [cell.contentView addSubview:self.segmentedPageViewController.view];
    [self.segmentedPageViewController didMoveToParentViewController:self];
    [self.segmentedPageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.contentView);
    }];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SCREENH_HEIGHT - SKStatusBar_Height - SKTabBar_Height;
}

//解决tableView在group类型下tableView头部和底部多余空白的问题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - HGSegmentedPageViewControllerDelegate
- (void)segmentedPageViewControllerWillBeginDragging {
    self.tableView.scrollEnabled = NO;
}

- (void)segmentedPageViewControllerDidEndDragging {
    self.tableView.scrollEnabled = YES;
}

#pragma mark - HGPageViewControllerDelegate
- (void)pageViewControllerLeaveTop {
    self.cannotScroll = NO;
}

#pragma mark - Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[HGCenterBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = NO;
            
        }
    }
    return _tableView;
}

- (UIImageView *)headerImageView {
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _HeaderImageViewHeight)];
        _headerImageView.image = [UIImage imageNamed:@"center_bg.jpg"];
        UIImageView * placeHolderImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * bannerRadio)];
        placeHolderImageView.image = SKIMAGE_NAMED(@"bannerPlacehoder");
        [_headerImageView addSubview:placeHolderImageView];
        _bannerView.placeholderImage = SKIMAGE_NAMED(@"bannerPlacehoder");
        _bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * bannerRadio) shouldInfiniteLoop:YES imageNamesGroup:@[]];
  
        UIImageView *iconImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, _HeaderImageViewHeight - 30, 80, 15)];
        iconImgView.contentMode = UIViewContentModeScaleAspectFit;
        iconImgView.image = [UIImage imageNamed:@"latestAnnouncement"];
        [_headerImageView addSubview:iconImgView];
        
        self.notifyView = [[YXLHomeNotifyView alloc] initWithFrame:CGRectMake(100, _HeaderImageViewHeight - 45, SCREEN_WIDTH-100, 45)];
        self.notifyView .clipsToBounds = YES;
        [_headerImageView addSubview:self.notifyView];
        _headerImageView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapNotifyView:)];
        
        [self.notifyView  addGestureRecognizer:tap];

    }
    return _headerImageView;
}

-(UIView *)topCoverView
{
    if (!_topCoverView) {
        _topCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, _HeaderImageViewHeight - SKStatusBar_Height, SCREEN_WIDTH, SKStatusBar_Height)];
        _topCoverView.backgroundColor = [UIColor whiteColor];
        _topCoverView.userInteractionEnabled = NO;
    }
    
    return _topCoverView;
}

- (HGSegmentedPageViewController *)segmentedPageViewController {
    if (!_segmentedPageViewController) {
        NSArray *titles = @[@"捡漏专区", @"精选专区", @"今日预购", @"今日历史"];
        NSArray *dataTypeArry = @[@(MainNewProductType), @(MainHotProductType), @(MainPurchaseProductType),@ (MainHistoryProductType)];
        NSMutableArray *controllers = [NSMutableArray array];
        for (int i = 0; i < titles.count; i++) {
            YXLProduceListViewController *controller = [[YXLProduceListViewController alloc] init];
            controller.dataType = [dataTypeArry[i] integerValue];
            controller.delegate = self;
            [controllers addObject:controller];
        }
        _segmentedPageViewController = [[HGSegmentedPageViewController alloc] init];
        
        _segmentedPageViewController.pageViewControllers = controllers.copy;
        _segmentedPageViewController.categoryView.titles = titles;
        _segmentedPageViewController.categoryView.originalIndex = self.selectedIndex;

        _segmentedPageViewController.delegate = self;
    }
    return _segmentedPageViewController;
}


-(void)tapNotifyView:(UITapGestureRecognizer *)tap
{
    if (self.notifyView.dataArry.count == 0) {
        return;
    }
    XMJSWebViewController *webVC = [[XMJSWebViewController alloc] init];
    
    NSDictionary *dataDic = self.notifyView.dataArry[self.notifyView.currentNum];
    
    //self.notifyDataArry
    
    webVC.type = WebType_H5_content;
    webVC.titleString = SafeString(dataDic[@"title"]);
    webVC.fileUrl = SafeString(dataDic[@"contents"]);
    [self.navigationController pushViewController:webVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)getTopADData
{
    NSDictionary *paramDic = @{};
    SKWeakSelf;
    [YQNetworking postWithUrl:@"Index/getBanner" refreshRequest:YES cache:NO params:paramDic progressBlock:nil successBlock:^(id response) {
        
        //NSDictionary *dataDic = response;
        NSArray *dataArry = [response arryWithFilted:@"data"];
        
        NSMutableArray * imageUrlArray = [[NSMutableArray alloc] initWithCapacity:0];
        
        for (NSDictionary *dic in dataArry) {
            NSString *urlStr = [dic stringWithFilted:@"imgurl"];
            [imageUrlArray addObject:urlStr];
        }
        if (imageUrlArray.count>0) {
            weakSelf.bannerView.imageURLStringsGroup = imageUrlArray;
            [weakSelf.headerImageView addSubview:weakSelf.bannerView];

        }
       
        
    } failBlock:^(NSError *error) {
        
    }];
}

-(void)getNotifyData
{
    NSDictionary *paramDic = @{@"type":@"1"};
    [YQNetworking postWithUrl:@"Index/getNotice" refreshRequest:YES cache:NO params:paramDic progressBlock:nil successBlock:^(id response) {
        self.notifyDataArry = [response arryWithFilted:@"data"];
        self.notifyView.dataArry = self.notifyDataArry;
        [self.notifyView runNotify];
    } failBlock:^(NSError *error) {
        
    }];
}




@end
